<template>
  <div style="width: 100%">
    <div align="center" ref="chartRef2" style="width: 1000px; height: 800px;"></div>
  </div>

</template>

<script setup name="Analysis">
import {defineProps, getCurrentInstance, onMounted, ref, watch,markRaw, onUnmounted} from "vue";
  // import data from "../../public/test.json"
  import * as echarts from 'echarts';

  const { proxy } = getCurrentInstance();
  const data = defineProps(['plotdata']);
  const chartRef2 = ref();
  const chartInstance = ref();
  // 初始化统计对象
  const cellNameCount = {};
  const cellNameSymbolCount = {};
  const uniqueSymbols = new Set(); // 用于存储唯一的symbol
  const uniqueCellNames = new Set(); // 用于存储唯一的cell_name

  // 根据p_value获取颜色
  const getColorFromPValue = (pValue) => {
    // p值越小，颜色越深
    // 定义颜色渐变的起始和结束颜色
    const startColor = '#f0e413'; // 浅黄色
    const endColor = '#1a8e8b'; // 深青色

    // 将十六进制颜色值转换为十进制
    const hexToRgb = (hex) => {
      let r = parseInt(hex.slice(1, 3), 16);
      let g = parseInt(hex.slice(3, 5), 16);
      let b = parseInt(hex.slice(5, 7), 16);
      return [r, g, b];
    };

    // 获取起始和结束颜色的RGB值
    const [r1, g1, b1] = hexToRgb(startColor);
    const [r2, g2, b2] = hexToRgb(endColor);

    // 将p值转换为0-1之间的比例，p值越小，比例越大
    // 假设p值范围在0-0.001之间
    const maxPValue = 0.001;
    const ratio = 1 - (pValue / maxPValue); // 反转比例，使p值越小，颜色越深

    // 使用RGB颜色插值计算渐变颜色
    const r = Math.round(r1 + (r2 - r1) * ratio);
    const g = Math.round(g1 + (g2 - g1) * ratio);
    const b = Math.round(b1 + (b2 - b1) * ratio);

    return `rgb(${r}, ${g}, ${b})`; // 返回计算出的颜色
  };

  // 根据snv_gene_number获取气泡大小
  const getSymbolSizeFromGeneNumber = (geneNumber) => {
    if (geneNumber <= 10) {
      return 5;
    } else if (geneNumber <= 25) {
      return 10;
    } else if (geneNumber <= 50) {
      return 15;
    } else {
      return 20;
    }
  };

  // 输出结果
  // console.log("Cell Name Count:", cellNameCount);
  // console.log("Cell Name Symbol Count:", cellNameSymbolCount);
  // console.log("Series Data:", seriesData);

watch(proxy.$props,(value)=>{
  // 清空之前的统计数据
  Object.keys(cellNameCount).forEach(key => delete cellNameCount[key]);
  Object.keys(cellNameSymbolCount).forEach(key => delete cellNameSymbolCount[key]);
  uniqueSymbols.clear();
  uniqueCellNames.clear();

  // 遍历数据
  value.plotdata.forEach(item => {
    const cellName = item.cell_name;
    const symbol = item.snv;  // 使用snv作为symbol

    // 统计cell_name出现的个数
    if (cellNameCount[cellName]) {
      cellNameCount[cellName]++;
    } else {
      cellNameCount[cellName] = 1;
    }

    // 统计每个cell_name下symbol出现的个数
    if (!cellNameSymbolCount[cellName]) {
      cellNameSymbolCount[cellName] = {};
    }
    if (cellNameSymbolCount[cellName][symbol]) {
      cellNameSymbolCount[cellName][symbol]++;
    } else {
      cellNameSymbolCount[cellName][symbol] = 1;
    }
    
    // 添加symbol到Set中，自动去重
    uniqueSymbols.add(symbol);

    // 添加cell_name到Set中，自动去重
    uniqueCellNames.add(cellName);
  });
  
  // 将Set转换为数组，作为x轴数据
  const xAxisData = Array.from(uniqueSymbols).sort();
  const yAxisData = Array.from(uniqueCellNames).sort();

  // 创建一个映射来存储每个(symbol, cellName)对应的数据项
  const dataMap = {};
  
  // 找出p_value的最小值和最大值
  let minPValue = Infinity;
  let maxPValue = 0;
  
  value.plotdata.forEach(item => {
    const key = `${item.snv}|${item.cell_name}`;
    dataMap[key] = item;
    
    // 更新p_value的最小值和最大值
    if (item.p_value < minPValue) {
      minPValue = item.p_value;
    }
    if (item.p_value > maxPValue) {
      maxPValue = item.p_value;
    }
  });
  
  // 确保最小值和最大值不相等，避免visualMap出错
  if (minPValue === maxPValue) {
    // 如果最小值和最大值相等，稍微调整最大值
    maxPValue = minPValue * 1.1 + 0.0001;
  }
  
  // 生成seriesData
  const seriesData = [];
  xAxisData.forEach((symbol, xIndex) => {
    yAxisData.forEach((cellName, yIndex) => {
      const count = cellNameSymbolCount[cellName]?.[symbol] || 0;
      if (count > 0) {
        const key = `${symbol}|${cellName}`;
        const dataItem = dataMap[key];
        seriesData.push([
          xIndex, 
          yIndex, 
          count,
          dataItem.snv_gene_number,
          dataItem.p_value
        ]);
      } else {
        seriesData.push([xIndex, yIndex, 0, 0, 0]);
      }
    });
  });

  chartInstance.value = markRaw(echarts.init(chartRef2.value));
  const option2 = {
  title: {
    text: ''
  },
  tooltip: {
    position: function (point, params, dom, rect, size) {
      return [point[0] + 10, point[1] - 60];
    },
    formatter: function (params) {
      if (params.value[2] === 0) return '';
      return (
        'SNV: ' + xAxisData[params.value[0]] + '<br/>' +
        'cell_type: ' + yAxisData[params.value[1]] + '<br/>' +
        'gene number: ' + params.value[3] + '<br/>' +
        'P-value: ' + params.value[4].toFixed(6)
      );
    },
    backgroundColor: 'rgba(255, 255, 255, 0.9)',
    borderColor: '#ccc',
    borderWidth: 1,
    padding: 10,
    textStyle: {
      color: '#333'
    }
  },
  grid: {
    left: 10,
    bottom: 80,
    right: 120,
    top: 20,
    containLabel: true
  },
  visualMap: [
    {
      type: 'continuous',
      min: 0,
      max: 0.001,
      precision: 6,
      calculable: true,
      orient: 'vertical',
      right: 10,
      top: 'middle',
      dimension: 4,
      text: ['P value\n0.001', '0'], // 使用换行符调整文本布局
      textStyle: {
        color: '#000',
        backgroundColor: 'transparent', // 设置文本框背景为透明
        borderWidth: 0, // 移除文本框边框
        padding: [0, 0, 0, 0] // 调整文本框内边距
      },
      inRange: {
        color: ['rgb(33, 76, 159)', 'rgb(237, 113, 96)'].reverse()
      }
    },
    {
      show: false,
      type: 'piecewise',
      orient: 'vertical',
      right: 10,
      bottom: 100,
      splitNumber: 4,
      dimension: 3,
      pieces: [
        { min: 1, max: 10, label: '≤ 10', symbol: 'circle', symbolSize: 10 },
        { min: 11, max: 25, label: '11-25', symbol: 'circle', symbolSize: 15 },
        { min: 26, max: 50, label: '26-50', symbol: 'circle', symbolSize: 20 },
        { min: 51, label: '> 50', symbol: 'circle', symbolSize: 25 }
      ],
      text: ['Count', ''],
      textStyle: {
        color: '#000'
      },
      itemSymbol: 'circle',
      showLabel: true,
      itemGap: 15,
      itemWidth: 30,
      itemHeight: 30
    }
  ],
  xAxis: {
    type: 'category',
    data: xAxisData,
    boundaryGap: false,
    splitLine: {
      show: true
    },
    axisLine: {
      show: false
    },
    axisLabel: {
      interval: 0,
      rotate: 45,
      margin: 15,
      fontSize: 12,
      align: 'right',
      verticalAlign: 'middle'
    }
  },
  yAxis: {
    type: 'category',
    data: yAxisData,
    axisLine: {
      show: false
    },
    axisLabel: {
      fontSize: 12
    }
  },
  series: [
    {
      name: 'Punch Card',
      type: 'scatter',
      symbolSize: function (val) {
        if (val[2] === 0) return 0;
        if (val[3] <= 10) {
          return 15;
        } else if (val[3] <= 25) {
          return 20;
        } else if (val[3] <= 50) {
          return 25;
        } else {
          return 30;
        }
      },
      data: seriesData,
      itemStyle: {
        color: function (params) {
          if (params.value[2] === 0) return 'rgba(0, 0, 0, 0)';
          return null;
        }
      },
      animationDelay: function (idx) {
        return idx * 5;
      }
    }
  ]
};
  chartInstance.value.setOption(option2);
  
  // 添加窗口大小变化时的自适应调整
  window.addEventListener('resize', function() {
    if (chartInstance.value) {
      chartInstance.value.resize();
    }
  });
})

// 组件卸载时移除事件监听
onUnmounted(() => {
  window.removeEventListener('resize', function() {
    if (chartInstance.value) {
      chartInstance.value.resize();
    }
  });
});
</script>

<style scoped>

</style>
